/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package paypal_bean;

import com.paypal.exception.*;
import com.paypal.sdk.exceptions.OAuthException;
import java.io.IOException;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.ParserConfigurationException;
import org.xml.sax.SAXException;
import urn.ebay.api.PayPalAPI.*;
import urn.ebay.apis.CoreComponentTypes.BasicAmountType;
import urn.ebay.apis.eBLBaseComponents.*;

/**
 *
 * @author vinh
 */
@ManagedBean(name = "ThanhToanTrucTuyen")
@SessionScoped
public class paypal {

    /**
     * Creates a new instance of paypal
     */
    public paypal() {
    }
    public static String token = "";
    public static String PayID = "";
    public static int TongTien = 0;

    /**
     * @return the token
     */
    public String getToken() {
        return token;
    }

    /**
     * @param token the token to set
     */
    public void setToken(String token) {
        paypal.token = token;
    }

    /**
     * @return the PayID
     */
    public String getPayID() {
        return PayID;
    }

    /**
     * @param PayID the PayID to set
     */
    public void setPayID(String PayID) {
        paypal.PayID = PayID;
    }

    /**
     * @return the TongTien
     */
    public int getTongTien() {
        return TongTien;
    }

    /**
     * @param TongTien the TongTien to set
     */
    public void setTongTien(int TongTien) {
        this.TongTien = TongTien;
    }

    public void SetCheckout() throws IOException {
        PayPalAPIInterfaceServiceService service = new PayPalAPIInterfaceServiceService(this.getClass().getResourceAsStream("/sdk_config.properties"));
        SetExpressCheckoutRequestType setExpressCheckoutReq = new SetExpressCheckoutRequestType();
        SetExpressCheckoutRequestDetailsType details = new SetExpressCheckoutRequestDetailsType();

        HttpServletRequest req = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
        String url = req.getRequestURL().toString();
        url=url.replaceFirst("/index.xhtml", "/");
        details.setReturnURL(url+"DoCheckout.jsp");

        details.setCancelURL(url+"error.xhtml");
        details.setBuyerEmail("vinh_1356661334_biz@yahoo.com");

        double itemTotal = TongTien;
        double orderTotal = TongTien;
        // populate line item details
        String amountItems = String.valueOf(TongTien);
        String qtyItems = "1";
        String names = "Dien Thoai";

        List<PaymentDetailsItemType> lineItems = new ArrayList<PaymentDetailsItemType>();

        PaymentDetailsItemType item = new PaymentDetailsItemType();
        BasicAmountType amt = new BasicAmountType();
        amt.setCurrencyID(CurrencyCodeType.fromValue("USD"));
        amt.setValue(amountItems);
        item.setQuantity(new Integer(qtyItems));
        item.setName(names);
        item.setAmount(amt);
        lineItems.add(item);

        List<PaymentDetailsType> payDetails = new ArrayList<PaymentDetailsType>();
        PaymentDetailsType paydtl = new PaymentDetailsType();
        paydtl.setPaymentAction(PaymentActionCodeType.fromValue("Sale"));
                //
        BasicAmountType shippingTotal = new BasicAmountType();
					shippingTotal.setValue("0.5");
					shippingTotal.setCurrencyID(CurrencyCodeType
							.fromValue("USD"));
					orderTotal += Double.parseDouble("0.5");
					paydtl.setShippingTotal(shippingTotal);
        //
        BasicAmountType itemsTotal = new BasicAmountType();
        itemsTotal.setValue(Double.toString(itemTotal));
        itemsTotal.setCurrencyID(CurrencyCodeType.fromValue("USD"));
        paydtl.setOrderTotal(new BasicAmountType(CurrencyCodeType.fromValue("USD"),
                Double.toString(orderTotal)));
        paydtl.setPaymentDetailsItem(lineItems);

        paydtl.setItemTotal(itemsTotal);
        paydtl.setNotifyURL("");

        payDetails.add(paydtl);
        details.setPaymentDetails(payDetails);
        
        setExpressCheckoutReq.setSetExpressCheckoutRequestDetails(details);

        SetExpressCheckoutReq expressCheckoutReq = new SetExpressCheckoutReq();
        expressCheckoutReq.setSetExpressCheckoutRequest(setExpressCheckoutReq);

        SetExpressCheckoutResponseType setExpressCheckoutResponse = null;
        try {
            setExpressCheckoutResponse = service.setExpressCheckout(expressCheckoutReq);
        } catch (SSLConfigurationException ex) {
            Logger.getLogger(paypal.class.getName()).log(Level.SEVERE, null, ex);
        } catch (InvalidCredentialException ex) {
            Logger.getLogger(paypal.class.getName()).log(Level.SEVERE, null, ex);
        } catch (HttpErrorException ex) {
            Logger.getLogger(paypal.class.getName()).log(Level.SEVERE, null, ex);
        } catch (InvalidResponseDataException ex) {
            Logger.getLogger(paypal.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ClientActionRequiredException ex) {
            Logger.getLogger(paypal.class.getName()).log(Level.SEVERE, null, ex);
        } catch (MissingCredentialException ex) {
            Logger.getLogger(paypal.class.getName()).log(Level.SEVERE, null, ex);
        } catch (InterruptedException ex) {
            Logger.getLogger(paypal.class.getName()).log(Level.SEVERE, null, ex);
        } catch (OAuthException ex) {
            Logger.getLogger(paypal.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ParserConfigurationException ex) {
            Logger.getLogger(paypal.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SAXException ex) {
            Logger.getLogger(paypal.class.getName()).log(Level.SEVERE, null, ex);
        }

        if (setExpressCheckoutResponse != null) {

            if (setExpressCheckoutResponse.getAck().toString().equalsIgnoreCase("SUCCESS")) {
                Map<Object, Object> map = new LinkedHashMap<Object, Object>();
                map.put("Ack", setExpressCheckoutResponse.getAck());
                map.put("Token", setExpressCheckoutResponse.getToken());
                map.put("Redirect URL",
                        "<a href=https://www.sandbox.paypal.com/cgi-bin/webscr?cmd=_express-checkout&token="
                        + setExpressCheckoutResponse.getToken()
                        + ">Redirect To PayPal</a>");
                token = setExpressCheckoutResponse.getToken();


                FacesContext context = FacesContext.getCurrentInstance();
                HttpServletResponse response = (HttpServletResponse) context.getExternalContext().getResponse();
                response.sendRedirect("https://www.sandbox.paypal.com/cgi-bin/webscr?cmd=_express-checkout&token=" + setExpressCheckoutResponse.getToken());
            } else {

                FacesContext.getCurrentInstance().getExternalContext().dispatch("/error.xhtml");
            }
        }
    }
    public void GetCheckout() throws IOException
    {
         PayPalAPIInterfaceServiceService service = new PayPalAPIInterfaceServiceService(this.getClass().getResourceAsStream("/sdk_config.properties"));
        GetExpressCheckoutDetailsReq req = new GetExpressCheckoutDetailsReq();
				GetExpressCheckoutDetailsRequestType reqType = new GetExpressCheckoutDetailsRequestType(
						token);
				req.setGetExpressCheckoutDetailsRequest(reqType);
				GetExpressCheckoutDetailsResponseType resp = null;
        try {
            resp = service
.getExpressCheckoutDetails(req);
        } catch (SSLConfigurationException ex) {
            Logger.getLogger(paypal.class.getName()).log(Level.SEVERE, null, ex);
        } catch (InvalidCredentialException ex) {
            Logger.getLogger(paypal.class.getName()).log(Level.SEVERE, null, ex);
        } catch (HttpErrorException ex) {
            Logger.getLogger(paypal.class.getName()).log(Level.SEVERE, null, ex);
        } catch (InvalidResponseDataException ex) {
            Logger.getLogger(paypal.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ClientActionRequiredException ex) {
            Logger.getLogger(paypal.class.getName()).log(Level.SEVERE, null, ex);
        } catch (MissingCredentialException ex) {
            Logger.getLogger(paypal.class.getName()).log(Level.SEVERE, null, ex);
        } catch (InterruptedException ex) {
            Logger.getLogger(paypal.class.getName()).log(Level.SEVERE, null, ex);
        } catch (OAuthException ex) {
            Logger.getLogger(paypal.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ParserConfigurationException ex) {
            Logger.getLogger(paypal.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SAXException ex) {
            Logger.getLogger(paypal.class.getName()).log(Level.SEVERE, null, ex);
        }
				if (resp != null) {
					if (resp.getAck().toString().equalsIgnoreCase("SUCCESS")) {
						
						
						token= resp.getGetExpressCheckoutDetailsResponseDetails()
								.getToken();
						PayID=resp.getGetExpressCheckoutDetailsResponseDetails()
								.getPayerInfo().getPayerID();
					
					} else {

					       
					}
				}
    }

    public boolean DoCheckout() throws IOException {
        
        PayPalAPIInterfaceServiceService service = new PayPalAPIInterfaceServiceService(this.getClass().getResourceAsStream("/sdk_config.properties"));
        DoExpressCheckoutPaymentRequestType doCheckoutPaymentRequestType = new DoExpressCheckoutPaymentRequestType();
        DoExpressCheckoutPaymentRequestDetailsType details = new DoExpressCheckoutPaymentRequestDetailsType();
       
        details.setToken(token);
        details.setPayerID(PayID);
        
        details.setPaymentAction(PaymentActionCodeType.fromValue("Sale"));

 double itemTotal = TongTien;
        double orderTotal = TongTien;
        // populate line item details
        String amountItems = String.valueOf(TongTien);
        String qtyItems = "1";
        String names = "Dien Thoai";

        List<PaymentDetailsItemType> lineItems = new ArrayList<PaymentDetailsItemType>();

        PaymentDetailsItemType item = new PaymentDetailsItemType();
        BasicAmountType amt = new BasicAmountType();
        amt.setCurrencyID(CurrencyCodeType.fromValue("USD"));
        amt.setValue(amountItems);
        item.setQuantity(new Integer(qtyItems));
        item.setName(names);
        item.setAmount(amt);
        lineItems.add(item);

        List<PaymentDetailsType> payDetails = new ArrayList<PaymentDetailsType>();
        PaymentDetailsType paydtl = new PaymentDetailsType();
        paydtl.setPaymentAction(PaymentActionCodeType.fromValue("Sale"));
              //
        BasicAmountType shippingTotal = new BasicAmountType();
					shippingTotal.setValue("0.5");
					shippingTotal.setCurrencyID(CurrencyCodeType
							.fromValue("USD"));
					orderTotal += Double.parseDouble("0.5");
					paydtl.setShippingTotal(shippingTotal);
        //
        BasicAmountType itemsTotal = new BasicAmountType();
        itemsTotal.setValue(Double.toString(itemTotal));
        itemsTotal.setCurrencyID(CurrencyCodeType.fromValue("USD"));
        paydtl.setOrderTotal(new BasicAmountType(CurrencyCodeType.fromValue("USD"),
                Double.toString(orderTotal)));
        paydtl.setPaymentDetailsItem(lineItems);

        paydtl.setItemTotal(itemsTotal);
        paydtl.setNotifyURL("");
        payDetails.add(paydtl);
        details.setPaymentDetails(payDetails);
        
        doCheckoutPaymentRequestType.setDoExpressCheckoutPaymentRequestDetails(details);
        DoExpressCheckoutPaymentReq doExpressCheckoutPaymentReq = new DoExpressCheckoutPaymentReq();
        doExpressCheckoutPaymentReq.setDoExpressCheckoutPaymentRequest(doCheckoutPaymentRequestType);

        DoExpressCheckoutPaymentResponseType doCheckoutPaymentResponseType = null;
        try {
            doCheckoutPaymentResponseType = service.doExpressCheckoutPayment(doExpressCheckoutPaymentReq);
        } catch (SSLConfigurationException ex) {
            Logger.getLogger(paypal.class.getName()).log(Level.SEVERE, null, ex);
        } catch (InvalidCredentialException ex) {
            Logger.getLogger(paypal.class.getName()).log(Level.SEVERE, null, ex);
        } catch (HttpErrorException ex) {
            Logger.getLogger(paypal.class.getName()).log(Level.SEVERE, null, ex);
        } catch (InvalidResponseDataException ex) {
            Logger.getLogger(paypal.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ClientActionRequiredException ex) {
            Logger.getLogger(paypal.class.getName()).log(Level.SEVERE, null, ex);
        } catch (MissingCredentialException ex) {
            Logger.getLogger(paypal.class.getName()).log(Level.SEVERE, null, ex);
        } catch (InterruptedException ex) {
            Logger.getLogger(paypal.class.getName()).log(Level.SEVERE, null, ex);
        } catch (OAuthException ex) {
            Logger.getLogger(paypal.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ParserConfigurationException ex) {
            Logger.getLogger(paypal.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SAXException ex) {
            Logger.getLogger(paypal.class.getName()).log(Level.SEVERE, null, ex);
        }

        if (doCheckoutPaymentResponseType != null) {

            if (doCheckoutPaymentResponseType.getAck().toString().equalsIgnoreCase("SUCCESS")) {
              
              
                Iterator<PaymentInfoType> iterator = doCheckoutPaymentResponseType.getDoExpressCheckoutPaymentResponseDetails().getPaymentInfo().iterator();
                int index = 1;
                while (iterator.hasNext()) {
                    PaymentInfoType result = (PaymentInfoType) iterator.next();
                 
                    index++;
                }
             
                return true;
               
            } else {
               
return false;
            }
        }
          return true;
    }
}
